package goComfyuiApi

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"

	"gitee.com/wchpub/fnsvr"
)

// 工作流执行请求
type PromptRequest struct {
	Prompt   WorkflowFmt `json:"prompt"`
	ClientId string      `json:"client_id"`
}

// 工作流执行响应
type PromptResponse struct {
	PromptID   string   `json:"prompt_id"`
	Number     int      `json:"number"` //在任务队列中的序号，值越小越靠前
	NodeErrors struct{} `json:"node_errors"`
}

// 执行工作流
func ApiExecuteWorkflow(comfyuiUrl, clientId, workflowId string, workflow WorkflowFmt, params []WorkflowParam) (string, error) {

	//遍历params
	for _, param := range params {
		if param.NodeId < 0 {
			continue //忽略负数的NodeId，通常是特殊节点
		}

		nodeInfo, ok := workflow[strconv.Itoa(param.NodeId)]
		if !ok {
			fnsvr.Log().Warn("ExecuteWorkflow node not found", "workflowId", workflowId, "nodeId", param.NodeId)
			continue
		}
		nodeInfo["inputs"].(map[string]interface{})[param.Name] = param.Value
	}

	// 创建执行请求
	promptReq := PromptRequest{
		Prompt:   workflow,
		ClientId: clientId,
	}

	//fnsvr.Log().Info("ExecuteWorkflow", "promptReq", promptReq)

	// 发送请求
	url := genComfyUIApiUrl(comfyuiUrl, "prompt")
	reqBody, err := json.Marshal(promptReq)
	if err != nil {
		return "", fmt.Errorf("failed to marshal prompt request: %v", err)
	}

	resp, err := http.Post(url, "application/json", bytes.NewBuffer(reqBody))
	if err != nil {
		return "", fmt.Errorf("failed to execute prompt: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		body, _ := io.ReadAll(resp.Body)
		return "", fmt.Errorf("prompt execution failed: %s", string(body))
	}

	var promptResp PromptResponse
	if err := json.NewDecoder(resp.Body).Decode(&promptResp); err != nil {
		return "", fmt.Errorf("failed to decode prompt response: %v", err)
	}

	return promptResp.PromptID, nil
}
